const vscode = require("vscode");
const util = require("../util.js");
const handle = require("./handle.js");
const interfaceVal = require("../interface/index.js");

let nodeID = null;
let wh = null
class daodanItem {
  constructor() {
    this._onDidChange = new vscode.EventEmitter();
    this.onDidChangeTreeData = this._onDidChange.event;
    this.itemList = [];
    this.userid = null;
    this.items = {
      xxx1: { id: "xxx1", name: "项目名称", type: "file", users: [] },
      xxx2: {
        id: "xxx2",
        name: "项目目录",
        type: "dir",
        children: [],
        users: [],
      },
    };
    this.ctx = null;
    this.interface1 = new interfaceVal.daodanInterface();
    this.handle = new handle.itemHandle(this.interface1);

  }
  getTreeItem(ele) {
    // console.log('getTreeItem',ele)
    return ele;
  }
  setctx(ct) {
    this.ctx = ct;
    this.interface1.setctx(ct)
    this.handle.setctx(ct);
    this._getLocalData();
    this.init();
    wh = this;
    // this._deleteAllData();
  }
  init() {
    const itemTreeView = vscode.window.createTreeView("daodan.item", {
      treeDataProvider: this,
    });
    itemTreeView.onDidChangeSelection(this.handle_node);
    this.ctx.subscriptions.push(itemTreeView);
    let that = this;
    let additem = vscode.commands.registerCommand(
      "daodan.addItem",
      function () {
        that.addItem();
      }
    );
    this.ctx.subscriptions.push(additem);

    let disposable_additemdir = vscode.commands.registerCommand(
      "daodan.addItemDir",
      function () {
        that.addItemDir();
      }
    );
    this.ctx.subscriptions.push(disposable_additemdir);
    let refresh = vscode.commands.registerCommand(
      "daodan.refreshItem",
      function () {
        that.refresh();
      }
    );
    this.ctx.subscriptions.push(refresh);
  }
  _getLocalData() {
    const itm = this.ctx.globalState.get("daodan.itemList");
    if (itm) {
      const itemList = JSON.parse(itm);
      this.itemList = [...itemList];
      // console.log("本地获取：", this.itemList);
      // console.log("所有：", this.ctx.globalState.keys());
    }
  }
  _deleteAllData() {
    let v = this.ctx.globalState.keys();
    for (var i in v) {
      this.ctx.globalState.update(v[i], null);
    }
  }
  addItem() {
    console.log("添加项目");
    const it = {
      id: util.getID("item"),
      name: "项目名称",
      type: "file",
      users: [this.userid],
      parent: null,
      before: [],
      after: [],
      global:{params:{},req:{headers:{},params:{},body:{},timeout:5000}},
      env:{'env_pro':{url:'',params:{},status:true,selected:true,name:'env_pro'},'env_pre':{url:'',params:{},status:false,selected:false,name:'env_pre'},'env_test':{url:'',params:{},status:false,selected:false,name:'env_test'},'env_dev':{url:'',params:{},status:false,selected:false,name:'env_dev'},'env_cus':{url:'',params:{},status:false,selected:false,name:'env_cus'}}
    };
    let that = this;
    vscode.window
      .showInputBox({
        prompt: "请输入新建的项目名称",
        placeHolder: "名称尽量不要重复",
      })
      .then((name) => {
        if (!name || name.trim().length == 0) {
          vscode.window.showErrorMessage("名称不能为空～");
          return;
        }
        it.name = name.trim();

      })
      .then(() => {
        if (nodeID) {
          let da = that.ctx.globalState.get(nodeID);
          if (!da) {
            vscode.window.showErrorMessage("项目参数异常,请重新点击选择～");
            return;
          }
          it.parent = nodeID;
          let itemdata = JSON.parse(da);
          if (itemdata && itemdata.type == "dir") {
            // 添加前后置
            it.before = [...itemdata.before]
            const before_id = util.getID('before');
            that.ctx.globalState.update(before_id, JSON.stringify({ 'position':'before','status': false, 'id': before_id, 'content': '//请使用 js 语法\n', 'it': it.id, 'name': '',time:0 }));
            it.before.push({status:true,id:before_id})
            it.after = [...itemdata.after]
            const after_id = util.getID('after');
            that.ctx.globalState.update(after_id, JSON.stringify({ 'position':'after','status': false, 'id': after_id, 'content': '//请使用 js 语法\n', 'it': it.id, 'name': '',time:0 }));
            it.after.push({status:true,id:after_id})
            // 以上是添加前后置
            that.ctx.globalState.update(it.id, JSON.stringify(it));
            itemdata.children.push(it.id);
            that.ctx.globalState.update(itemdata.id, JSON.stringify(itemdata));
            that.refresh();
            return;
          }else {
            vscode.window.showWarningMessage("选中非文件夹，请选择文件夹或者清除选中～");
            return;
          }
        }
        // 添加前后置
        const before_id = util.getID('before');
        that.ctx.globalState.update(before_id, JSON.stringify({ 'position':'before','status': false, 'id': before_id, 'content': '//请使用 js 语法\n', 'it': it.id, 'name': '',time:0 }));
        it.before.push({status:true,id:before_id})
        const after_id = util.getID('after');
        that.ctx.globalState.update(after_id, JSON.stringify({ 'position':'after','status': false, 'id': after_id, 'content': '//请使用 js 语法\n', 'it': it.id, 'name': '',time:0 }));
        it.after.push({status:true,id:after_id})
        // 以上是添加前后置
        that.ctx.globalState.update(it.id, JSON.stringify(it));
        that.itemList.push(it.id);
        that.ctx.globalState.update(
          "daodan.itemList",
          JSON.stringify(that.itemList)
        );
        that.refresh();
      });
  }
  addItemDir() {
    console.log("添加项目目录");
    const it = {
      id: util.getID("itemDir"),
      name: "项目目录",
      type: "dir",
      children: [],
      users: [this.userid],
      parent: null,
      before: [],
      after: []
    };
    let that = this;
    vscode.window
      .showInputBox({
        prompt: "请输入新建的项目目录",
        placeHolder: "名称尽量不要重复",
      })
      .then((name) => {
        if (!name || name.trim().length == 0) {
          vscode.window.showErrorMessage("名称不能为空～");
          return;
        }
        it.name = name.trim();
      })
      .then(() => {
        if (nodeID) {
          let da = that.ctx.globalState.get(nodeID);
          if (!da) {
            vscode.window.showErrorMessage("项目参数异常,请重新点击选择～");
            return;
          }
          it.parent = nodeID
          let itemdata = JSON.parse(da);
          if (itemdata && itemdata.type == "dir") {
            // 添加前后置
            it.before = [...itemdata.before]
            const before_id = util.getID('before');
            that.ctx.globalState.update(before_id, JSON.stringify({ 'status': false, 'id': before_id, 'content': '//请使用 js 语法\n', 'it': it.id, 'name': '' }));
            it.before.push({status:true,id:before_id})
            it.after = [...itemdata.after]
            const after_id = util.getID('after');
            that.ctx.globalState.update(after_id, JSON.stringify({ 'status': false, 'id': after_id, 'content': '//请使用 js 语法\n', 'it': it.id, 'name': '' }));
            it.after.push({status:true,id:after_id});
            // 以上是添加前后置

            that.ctx.globalState.update(it.id, JSON.stringify(it));
            itemdata.children.push(it.id);
            that.ctx.globalState.update(itemdata.id, JSON.stringify(itemdata));
            that.refresh();
            return;
          } else {
            vscode.window.showWarningMessage("选中非文件夹，请选择文件夹或者清除选中～");
            return;
          }
        }
        // 添加前后置
        const before_id = util.getID('before');
        that.ctx.globalState.update(before_id, JSON.stringify({ 'status': false, 'id': before_id, 'content': '//请使用 js 语法\n', 'it': it.id, 'name': '' }));
        it.before.push({status:true,id:before_id})
        const after_id = util.getID('after');
        that.ctx.globalState.update(after_id, JSON.stringify({ 'status': false, 'id': after_id, 'content': '//请使用 js 语法\n', 'it': it.id, 'name': '' }));
        it.after.push({status:true,id:after_id});
         // 以上是添加前后置
        that.ctx.globalState.update(it.id, JSON.stringify(it));
        that.itemList.push(it.id);
        that.ctx.globalState.update(
          "daodan.itemList",
          JSON.stringify(that.itemList)
        );
        that.refresh();
      });
  }
  handle_node(event) {
    let se = event.selection;
    if (se && se.length > 0) {
      nodeID = se[0].id;
    } else {
      nodeID = null;
    }
  }
  getChildren(ele) {
    const selectItem = this.ctx.globalState.get("daodan.selectItem");
    // console.log("selectItem",selectItem)
    if (ele) {
      // console.log("ineer", ele, ele.id);
      let itemData = this.ctx.globalState.get(ele.id);
      if (!itemData) {
        vscode.window.showInformationMessage(ele.id + ",子项目不存在");
        console.log(ele.id + ",子项目不存在");
        return;
      }
      let da = JSON.parse(itemData);
      if (da && da.children && da.children.length > 0) {
        return this.getItemTree(da.children, true, selectItem);
      }
      return [];
    } else {
      // console.log("getroot",this.itemList);
      return this.getItemTree(this.itemList, false, selectItem);
    }
  }
  refresh(userid) {
    if (userid) {
      this.userid = userid;
    }
    if (userid == 0) {
      this.userid = null;
    }
    this.interface1.refresh(nodeID, this.userid ? this.userid : 0);
    this._getLocalData();
    this._onDidChange.fire();
  }

  getItemTree(vals, isChildren, selectItem) {
    console.log("getItemTree", vals,isChildren,selectItem);
    let tmp = [];
    if (!this.userid) {
      vscode.window.showInformationMessage("请先在左下角登录～");
      return;
    }
    for (let index in vals) {
      let itemData = this.ctx.globalState.get(vals[index]);
      if (!itemData) {
        vscode.window.showInformationMessage(vals[index] + ",项目不存在");
        console.log(vals[index] + ",项目不存在");
        continue;
      }
      // console.log("itemData",itemData);
      itemData = JSON.parse(itemData);
      if (
        !itemData.users ||
        itemData.users.length == 0 ||
        itemData.users.indexOf(this.userid) == -1
      ) {
        continue;
      }
      let icon = vscode.TreeItemCollapsibleState.None;
      if (itemData.type == "dir") {
        if (isChildren) {
          icon = vscode.TreeItemCollapsibleState.Collapsed;
        } else {
          icon = vscode.TreeItemCollapsibleState.Expanded;
        }
      }
      tmp.push(new itemTree(itemData.name, icon, itemData.id, this.interface1, selectItem));
    }
    return tmp;
  }
}

class itemTree extends vscode.TreeItem {
  constructor(label, collapsible, id, interface1, selectItem) {
    let label_one = label
    super(label_one, collapsible);
    this.tooltip = label_one;
    this.id = id;
    this.interface1 = interface1
    if (collapsible == vscode.TreeItemCollapsibleState.None) {
      if (id == selectItem) {
        this.iconPath = new vscode.ThemeIcon("arrow-small-right");
      } else {
        this.iconPath = new vscode.ThemeIcon("none");
      }
      this.contextValue = "file";
    } else {
      this.iconPath = new vscode.ThemeIcon("folder");
      this.contextValue = "dir";
    }
    this.command = {
      title: "test",
      command: "daodan.itemHandle",
      arguments: [this],
    };
  }

  // command = {
  //   title: "test",
  //   command: "daodan.nihao",
  //   arguments: [],
  // };
}

module.exports = {
  daodanItem,
};
